<template>
  <div>
    <!-- 1.这是头部查询参数（按单位/人员、是否过期、关键字进行资质证照的查询；）   -->
    <div class="bg-white h-auto my-2 mx-2 mb-2 py-4">
      <BasicForm @register="registerForm" @submit="handleSubmit" />
    </div>

    <!-- 2.这是显示内容   -->
    <BasicTable @register="registerTable" :data-source="tableData" size="small" :can-resize="true" :bordered="true"
                :striped="true">
      <template #holdusername="{ record }">
        {{ record.holdusername || '本单位' }}
      </template>
      <template #isvalid="{ record }">
        <Tag :color="record.isvalid === true ? 'green' : 'red'">
          {{ record.isvalid === true ? '有效' : '已过期' }}
        </Tag>
      </template>
      <template #toolbar>
        <a-button type="primary" @click="handleAdd">新增</a-button>
      </template>
<!--      <template #isepiboly="{ record }">
        <Tag :color="record.isepiboly === true ? 'green' : 'red'">
          {{ record.isepiboly === true ? '是' : '否' }}
        </Tag>
      </template>-->

<!--      <template #isperson="{ record }">
        <Tag :color="record.isperson === true ? 'blue' : 'orange'">
          {{ record.isperson === true ? '人员证照' : '单位证照' }}
        </Tag>
      </template>-->
      <template #action="{ record }">
        <TableAction :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '修改',
              onClick: onEditData.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: onDeleteData.bind(null, record),
              },
            },
            {
              icon: 'ant-design:eye-outlined',
              label: '附件',
              onClick: handleAttachment.bind(null, record),
            },
          ]" />
      </template>
    </BasicTable>

    <!-- 3.公共弹出框   -->
    <!-- 3.1 增加和修改  -->
    <AddOrUpdateCertificateInfo @register="registerAddOrUpdateModal" @success="handleSuccess" />
    <!-- 3.2 附件显示  -->
    <AttachmentModal @register="registerAttachmentModal" />
  </div>
</template>
<script lang="ts">
import { useGlobSetting } from '/@/hooks/setting';
import { getUserOrganization } from '/@/api/ehs/organization';
const { globalProjectCode } = useGlobSetting();
import { BasicForm, useForm } from '/@/components/Form';
import { BasicTable, TableAction, useTable } from '/@/components/Table';
import {
  certificateInfoTableColumns,
  certificateInfoTableQueryConditionFormSchemas,
} from '/@/views/ehs/certificateInfo/certificateInfo.data';
import {defineComponent, onMounted, ref, computed, nextTick, provide} from 'vue';
import { Tag } from 'ant-design-vue';
import { useMessage } from '/@/hooks/web/useMessage';
const { createMessage } = useMessage();
import {deleteCertificateInfo, queryCertificateInfo} from '/@/api/ehs/certificateInfo';
import loading from '/@/directives/loading';
import { CertificateQueryConditionDto } from '/@/api/ehs/model/certificateInfoModel';
import { useModal } from '/@/components/Modal';
import AttachmentModal from '/@/views/ehs/certificateInfo/AttachmentModal.vue';
import AddOrUpdateCertificateInfo from '/@/views/ehs/certificateInfo/AddOrUpdateCertificateInfo.vue';
import {OperationTypeEnum} from "/@/enums/appEnum";

export default defineComponent({
  name: 'CertificateInfoIndex',
  components: {
    AddOrUpdateCertificateInfo,
    AttachmentModal,
    Tag,
    TableAction,
    BasicForm,
    BasicTable,
  },
  setup() {
    provide('moduleName', '资质证照');

    const projectCode = ref(globalProjectCode);
    const organizationCode = ref('');
    // 表格数据
    const tableData = ref([]);

    // 相关方数据存储
    const epibolyData = ref({
      units: [], // 单位相关方列表：[{id, name}]
      persons: [] // 人员相关方列表：[{id, name}]
    });

    // 当前表单值
    const currentFormValues = ref({
      holdtype: '',
      isepiboly: false
    });

    // 计算属性：动态相关方选项
    const epibolyOptions = computed(() => {
      const { holdtype, isepiboly } = currentFormValues.value;

      // 如果未选中相关方，返回空数组
      if (!isepiboly) {
        return [];
      }

      let options = [];

      if (!holdtype || holdtype === '') {
        // 全部类型：显示单位+人员，添加类型标识
        const unitOptions = epibolyData.value.units.map(item => ({
          label: `${item.name}（单位）`,
          value: `unit_${item.id}`,
          type: 'unit'
        }));

        const personOptions = epibolyData.value.persons.map(item => ({
          label: `${item.name}（人员）`,
          value: `person_${item.id}`,
          type: 'person'
        }));

        options = [...unitOptions, ...personOptions];

      } else if (holdtype === '1') {
        // 单位资质：只显示单位选项
        options = epibolyData.value.units.map(item => ({
          label: item.name,
          value: item.id,
          type: 'unit'
        }));

      } else if (holdtype === '2') {
        // 人员资质：只显示人员选项
        options = epibolyData.value.persons.map(item => ({
          label: item.name,
          value: item.id,
          type: 'person'
        }));
      }

      return options;
    });

    // 注册附件模态框
    const [registerAttachmentModal, { openModal: openAttachmentModal }] = useModal({});

    // 注册新增/修改模态框
    const [registerAddOrUpdateModal, { openModal: openAddOrUpdateModal }] = useModal({});

    // 注册表单 - 使用原始schema
    const [registerForm, { setFieldsValue, getFieldsValue, resetFields, submit, updateSchema }] = useForm({
      labelWidth: 80,
      schemas: certificateInfoTableQueryConditionFormSchemas, // 使用原始schema
      showResetButton: false,
      showSubmitButton: true,
      rowProps: {
        gutter: [10], // 设置间距
      },
      actionColOptions: {
        span: 24,
      },

    });

    // 注册表格
    const [registerTable, { reload, getForm }] = useTable({
      title: '资质证照管理',
      columns: certificateInfoTableColumns,
      showTableSetting: true,
      bordered: true,
      useSearchForm: false,
      formConfig: {
        labelWidth: 80,
        schemas: certificateInfoTableQueryConditionFormSchemas,
        showResetButton: false,
      },
      showTableSetting: true, //是否显示表格设置
      showIndexColumn: true,
      actionColumn: {
        width: 150,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
      },
      pagination: false, //分页
    });

    // 获取相关方数据函数
    async function fetchEpibolyList() {
      try {

        const baseParams = {
          orgcode: organizationCode.value,
          isepiboly: true,
          keywords: '',
          status: '',
        };

        // 并行请求单位和人员数据
        const [unitResult, personResult] = await Promise.all([
          queryCertificateInfo({ ...baseParams, holdtype: '1' }),
          queryCertificateInfo({ ...baseParams, holdtype: '2' })
        ]);

        // 提取唯一的单位相关方
        const units = [];
        const unitIds = new Set();
        if (unitResult && Array.isArray(unitResult)) {
          unitResult.forEach((item) => {
            if (item.holduserid && item.holdusername && !unitIds.has(item.holduserid)) {
              unitIds.add(item.holduserid);
              units.push({
                id: item.holduserid,
                name: item.holdusername
              });
            }
          });
        }

        // 提取唯一的人员相关方
        const persons = [];
        const personIds = new Set();
        if (personResult && Array.isArray(personResult)) {
          personResult.forEach((item) => {
            if (item.holduserid && item.holdusername && !personIds.has(item.holduserid)) {
              personIds.add(item.holduserid);
              persons.push({
                id: item.holduserid,
                name: item.holdusername
              });
            }
          });
        }

        // 更新相关方数据
        epibolyData.value = { units, persons };

        // 数据加载完成后，立即更新一次schema
        updateEpibolySchema();

      } catch (error) {
        console.error('获取相关方列表失败', error);
        createMessage.error('获取相关方数据失败');
      }
    }

    // 更新相关方下拉schema的函数
    function updateEpibolySchema() {
      const options = epibolyOptions.value;

      updateSchema({
        field: 'epiboly',
        componentProps: {
          fieldNames: {
            label: 'label',
            value: 'value'
          },
          options: options,
          placeholder: '请选择相关方名称'
        }
      });
    }

    // 监听表单值变化并更新当前值
    function handleFormValuesChange() {
      const values = getFieldsValue();
      const newValues = {
        holdtype: values.holdtype || '',
        isepiboly: values.isepiboly || false
      };

      // 检查是否有实际变化
      const hasChanged =
          currentFormValues.value.holdtype !== newValues.holdtype ||
          currentFormValues.value.isepiboly !== newValues.isepiboly;

      if (hasChanged) {

        // 更新当前表单值
        currentFormValues.value = newValues;

        // 更新相关方下拉选项
        nextTick(() => {
          updateEpibolySchema();

          // 清空相关方选择，避免类型不匹配
          const allValues = getFieldsValue();
          if (allValues.epiboly) {
            setFieldsValue({ ...allValues, epiboly: undefined });
          }
        });
      }
    }

    // 处理表单提交
    async function handleSubmit(values: any) {
      try {
        loading.value = true;

        // 同步表单值
        currentFormValues.value = {
          holdtype: values.holdtype || '',
          isepiboly: values.isepiboly || false
        };

        const isEpibolyBool = values.isepiboly === true || values.isepiboly === 'true' || values.isepiboly === '1';
        const params: CertificateQueryConditionDto = {
          orgcode: organizationCode.value,
          isepiboly: isEpibolyBool,
          keywords: values.keywords || '',
          holdtype: values.holdtype || '',
          status: values.status || '',
        };

        // 处理相关方参数
        if (isEpibolyBool && values.epiboly) {
          if (typeof values.epiboly === 'string' && values.epiboly.includes('_')) {
            const [type, id] = values.epiboly.split('_');
            params.epiboly = id;
          } else {
            params.epiboly = values.epiboly;
          }
        } else {
          params.epiboly = '';
        }

        const result = await queryCertificateInfo(params);
        tableData.value = result || [];

      } catch (error) {
        console.error('查询资质证照失败', error);
        createMessage.error('查询失败');
      } finally {
        loading.value = false;
      }
    }

    // 处理附件显示
    function handleAttachment(record: Recordable) {
      openAttachmentModal(true, {
        record,
      });
    }

    // 处理新增
    function handleAdd() {
      openAddOrUpdateModal(true, {
        operateType: OperationTypeEnum.ADD,
        orgcode: organizationCode.value,
        moduleName: '资质证照'
      });
    }

    function handleSuccess() {
      submit();
      //重新获取相关方列表
      fetchEpibolyList();
    }

    //处理修改数据
    function onEditData(record: Recordable) {
      openAddOrUpdateModal(true, {
        operateType: OperationTypeEnum.EDIT,
        orgcode: organizationCode.value,
        moduleName: '资质证照',
        id: record.id,
      });
    }

    //处理删除数据
    function onDeleteData(record: Recordable) {
      deleteCertificateInfo(record.id)
          .then((res) => {
            if (res === undefined || res === null || (typeof res === 'object' && Object.keys(res).length === 0)) {
              createMessage.success('删除成功。', 2);
              submit(); // 刷新数据
            } else {
              createMessage.error('删除失败。', 2);
            }
          });
    }

    // 页面初始化
    onMounted(async () => {
      try {
        //获取用户组织信息
        const orgResult= await  getUserOrganization()
        if (orgResult?.orgcode){
          organizationCode.value=orgResult.orgcode;
        }else {
          console.warn('未获取到组织代码，使用默认值');
        }
      }catch (error){
        console.error('获取组织信息失败', error)
        createMessage.error('获取组织信息失败，使用默认配置')
      }
      // 加载相关方数据
      await fetchEpibolyList();

      // 设置初始表单值
      const initialValues = getFieldsValue();
      currentFormValues.value = {
        holdtype: initialValues.holdtype || '',
        isepiboly: initialValues.isepiboly || false
      };

      // 添加表单字段变化监听器
      updateSchema([
        {
          field: 'holdtype',
          componentProps: {
            options: [
              { label: '全部', value: '' },
              { label: '单位资质', value: '1' },
              { label: '人员资质', value: '2' },
            ],
            onChange: (value) => {
              setTimeout(() => {
                handleFormValuesChange();
              }, 50); // 短暂延迟确保值已更新
            },
          },
        },
        {
          field: 'isepiboly',
          componentProps: {
            onChange: (checked) => {
              setTimeout(() => {
                handleFormValuesChange();
              }, 50); // 短暂延迟确保值已更新
            },
          },
        }
      ]);

      // 执行初始查询
      handleSubmit({});
    });

    return {
      AddOrUpdateCertificateInfo,
      AttachmentModal,
      submit,
      registerForm,
      registerTable,
      tableData,
      handleSubmit,
      handleAdd,
      onEditData,
      onDeleteData,
      handleAttachment,
      registerAttachmentModal,
      registerAddOrUpdateModal,
      handleSuccess
    };
  },
});
</script>
<style lang="less"></style>
